import json
import random
import time
from datetime import datetime

import pymysql
import requests

from Base import Log
from Base.GetYamlFile import getYamlPath
from Base.HttpBase import HttpBase

log = Log.Log()
base_url = 'http://192.168.17.236:30510'  # 独立租户1环境
login_api = base_url + '/upms-provider/tenant/user/login/mobile'
login_data = {
    'mobile': '18368093710',
    'password': 'Aa123456'
}
headers = {
    'Content-Type': 'application/json'
}
token = HttpBase(login_api, login_data, 'post', headers).getHttpHeaders().get('access_token')
Refresh_token = HttpBase(login_api, login_data, 'post', headers).getHttpHeaders().get('Refresh_token')

base_data = {
    'orderId': 141098578501701,
    'tenantId': 1,
    'customerId': 30817,
    'customerName': '对账企业',
    'orderGoodsId': 141098578690117,
    'licensePlate': '浙C00001',
    'driverPhone': '18368033333',
}

# 基础请求头
base_headers = {
    'type': 'tenant',
    'tenant_id': str(base_data.get('tenantId')),
    'access_token': token,
    'Refresh_token': Refresh_token,
    # 'Version': 'middleground-2.0.5.6-SNAPSHOT'
}

story_dp_order_headers = base_headers
story_dp_order_headers['Content-Type'] = 'application/json'

'''
发货单创建接口,num代表要创建的发货单号次数，order_num代表要创建发货单关联订单num
'''


def create_dp_order_test(num, order_num):
    sql_config = getYamlPath("SqlConfigConcrete")
    basic_conn = pymysql.connect(**sql_config)
    cur = basic_conn.cursor()
    # 根据手机号获取司机名称及id赋值
    select_sql = '''
                    SELECT
                        sog.id as iROWNo,
                        sog.category_code as cInvCCode,
                        sog.product_code as cInvCode , 
                        so.customer_code as KHBM,
                        so.customer_name as KHMC,
                        so.project_id as  ProjectCode,
                        so.project_name as GDMC,
                        sog.construction_position as SGBW,
                        sog.construction_method_name as SGFS,
                        sog.construction_equipment_name as SGSB,
                        so.address as cCusOAddress,
                        so.contact as ccusperson,
                        sog.model_material as TQD,
                        so.create_time as FCRQ
                    FROM
                        sales_order_goods sog
                        left join sales_order so  on so.id =sog.order_id
                    WHERE
                        sog.order_id IN ( SELECT id FROM sales_order WHERE order_num = %s AND genre = 1 );
                '''
    test_data = order_num
    test = cur.execute(select_sql, test_data)
    test = cur.fetchall()
    i = 0
    xh_list = []
    while i < num:
        for item in test:
            # 发货单单号
            print(item)
            story_dp_order_url = base_url + '/tenant-commercial-concrete-provider/api/sales/production/storyDpOrder'
            xh = str(datetime.now().month) + str(datetime.now().day) + str(datetime.now().hour) + str(
                datetime.now().minute) + str(
                datetime.now().second) + str(datetime.now().microsecond)
            data = {
                "XH": xh,
                "FCRQ": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                "ZDR": "林洲",
                "iROWNo": str(item[0]),
                "cSOcode": test_data,
                "cInvCode": item[2],
                "cInvCCode": item[1],
                "KHBM": item[3],
                "KHMC": item[4],
                "ProjectCode": str(item[5]),
                "GDMC": item[6],
                "SGBW": item[7],
                "SGFS": item[8],
                "SGSB": item[9],
                "cCusOAddress": item[10],
                "ccusperson": item[11],
                "SCXID": "5",
                "CH": "3#",
                "CPHM": "浙A17551",
                "PBBH": "1133",
                "TQD": item[12],
                "SL": random.randint(1, 10),
                "ENDTime": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                "FCID": "1",
                "SHID": "0",
                "SHR": "",
                "SHTime": "",
                "BZ": "test",
                "SendState": "1",
                "SendResults": "发送成功",
                "TLD": "15±1"
            }
            # log.info("请求数据：%s" % data)
            log.info(json.dumps(data, ensure_ascii=False))
            result = requests.post(story_dp_order_url, json=data, headers=story_dp_order_headers)
            log.info(json.loads(str(result.content, 'utf-8')))
            xh_list.append(xh)
        i += 1
    return xh_list


'''
发货单审核接口，根据发货单号
'''


def check_dp_order_test(xh_list):
    check_url = base_url + '/tenant-commercial-concrete-provider/api/sales/production/check'
    if type(xh_list) is list:
        for xh in xh_list:
            check_data = {
                "XH": xh,
                "SHID": 1,
                "SHTime": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                "SHR": "林洲"
            }
            result = requests.post(check_url, json=check_data, headers=story_dp_order_headers)
            log.info(str(result.content, 'utf-8'))
    else:
        check_data = {
            "XH": xh_list,
            "SHID": 1,
            "SHTime": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            "SHR": "林洲"
        }
        log.info(json.dumps(check_data, ensure_ascii=False))
        result = requests.post(check_url, json=check_data, headers=story_dp_order_headers)
        log.info(str(result.content, 'utf-8'))


'''
发货单更新接口，根据发货单号
'''


def update_dp_order_test(xh_list):
    update_dp_order_url = base_url + '/tenant-commercial-concrete-provider/api/sales/production/updateDpOrder'
    if type(xh_list) is list:
        for xh in xh_list:
            update_data = {
                "XH": xh,
                # "SL": random.randint(1, 10),
                "SHID": "0"
            }

            result = requests.post(update_dp_order_url, json=update_data, headers=story_dp_order_headers)
            log.info(str(result.content, 'utf-8'))
    else:
        update_data = {
            "XH": xh_list,
            # "SL": random.randint(1, 10),
            "SHID": "0"
        }

        result = requests.post(update_dp_order_url, json=update_data, headers=story_dp_order_headers)
        log.info(str(result.content, 'utf-8'))


if __name__ == '__main__':
    # xh = str(datetime.now().month) + str(datetime.now().day) + str(datetime.now().hour) + str(
    #     datetime.now().minute) + str(
    #     datetime.now().second) + str(datetime.now().microsecond)
    xh_list = create_dp_order_test(2, 'SO20240618597175')
    time.sleep(1)
    # update_dp_order_test(xh_list)
    check_dp_order_test(xh_list)
